<template>
  <el-dialog v-model="dialogVisible" :title="parameter.title" width="710px" lock-scroll destroy-on-close draggable>
    <el-form ref="formRef" :model="parameter.mail" label-width="100px" label-suffix=" :">
      <el-form-item label="标题" prop="title" :rules="[{ required: true, message: '站内信标题不可为空', trigger: 'blur' }]">
        <el-input v-model="parameter.mail.title" placeholder="请输入标题" clearable>
          <template #prepend>
            <el-select v-model="parameter.mail.mailType" style="width: 115px">
              <el-option v-for="item in mailTypeConst" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        label="发送范围"
        prop="sendingRange"
        :rules="[{ required: true, message: '发送范围不可为空', trigger: 'blur' }]"
      >
        <el-select v-model="parameter.mail.sendingRange" placeholder="请选择类型" clearable>
          <el-option v-for="item in mailSendingRangeConst" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="parameter.mail.sendingRange === 1"
        label="指定机构"
        prop="orgId"
        :rules="[{ required: true, message: '接收机构不能为空', trigger: 'blur' }]"
      >
        <el-cascader
          v-model="parameter.mail.orgId"
          :options="formInline.orgOptions"
          :props="{ checkStrictly: true, emitPath: false }"
          style="width: 100%"
          clearable
          filterable
          placeholder="请选择接收信息的机构"
        >
          <template #default="{ node, data }">
            <span>{{ data.label }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item
        v-if="parameter.mail.sendingRange === 2"
        label="指定角色"
        prop="roleIds"
        :rules="[{ required: true, message: '接收角色不能为空', trigger: 'blur' }]"
      >
        <el-select v-model="parameter.mail.roleIds" placeholder="请分配用户角色" multiple clearable>
          <el-option v-for="item in formInline.roleOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="parameter.mail.sendingRange === 3"
        label="指定用户"
        prop="userIds"
        :rules="[{ required: true, message: '接收用户不能为空', trigger: 'blur' }]"
      >
        <el-transfer
          v-model="parameter.mail.userIds"
          :data="formInline.userOptions"
          filterable
          :titles="['用户列表', '接收用户']"
          :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}'
          }"
          :props="{ key: 'userId', disabled: 'isEnable' }"
        >
          <template #default="{ option }">
            <span style="display: flex; align-items: center">
              <el-avatar :src="option.avatar" size="small" />
              <span style="margin-left: 4px">{{ option.nickName }}</span>
            </span>
          </template>
        </el-transfer>
      </el-form-item>
      <el-form-item label="消息内容" prop="message" :rules="[{ required: true, message: '消息内容不可为空', trigger: 'blur' }]">
        <wang-editor
          v-model:value="parameter.mail.message!"
          :toolbar-config="{
            toolbarKeys: ['fontFamily', 'fontSize', 'color', 'bold', 'underline', 'uploadImage']
          }"
          height="300px"
          model="simple"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance } from "element-plus";
import type { ResultData, Option, SysUser, SysMail } from "@/api/interface";
import { ref, reactive } from "vue";
import { mailTypeConst, mailSendingRangeConst } from "@/utils/dict";
import { ElMessage } from "element-plus";
import { getOrgCascaderOptionApi } from "@/api/modules/system/org";
import { getRoleOptionApi } from "@/api/modules/system/role";
import { getAllUserApi } from "@/api/modules/system/user";
import WangEditor from "@/components/WangEditor/index.vue";

/** 系统消息 */
interface EditProps {
  /** 标题 */
  title: string;
  /** 待编辑的消息 */
  mail: Partial<SysMail.Form>;
  /** 获取表格数据的Api */
  getTableList?: () => void;
  /** 提交表单的Api */
  submitApi?: (params: any) => Promise<ResultData<boolean>>;
}
/** 表单内联数据 */
interface FormInline {
  /** 机构选项 */
  orgOptions: Option.CascadeOption[];
  /** 角色选项 */
  roleOptions: Option.SelectOption[];
  /** 用户选项 */
  userOptions: SysUser.InfoResult[];
}

/** 表单实例 */
const formRef = ref<FormInstance>();
/** dialog 状态 */
const dialogVisible = ref(false);
/** 父组件传过来的参数 */
const parameter = ref<EditProps>({
  title: "",
  mail: {}
});
/** 表单内联数据 */
const formInline = reactive<FormInline>({
  orgOptions: [],
  roleOptions: [],
  userOptions: []
});

/**
 * 接收父组件参数
 *
 * @param params 父组件传过来的参数
 * @returns void
 */
const acceptParams = (params: EditProps) => {
  parameter.value = params;
  dialogVisible.value = true;

  // 获取机构选项
  getOrgCascaderOptionApi().then(({ data }) => {
    formInline.orgOptions = data;
  });

  // 获取角色选项
  getRoleOptionApi().then(({ data }) => {
    formInline.roleOptions = data;
  });

  // 获取用户选项
  getAllUserApi().then(({ data }) => {
    data.map((item: SysUser.InfoResult) => {
      item.isEnable = !item.isEnable;
    });
    formInline.userOptions = data;
  });
};

/**
 * 提交表单
 *
 * 1. 校验表单
 * 2. 处理表单数据
 * 3. 提交表单
 * 4. 提交结果处理
 * 5. 异常处理
 *
 * @returns void
 */
const handleSubmit = () => {
  formRef.value
    // 1. 校验表单
    ?.validate()
    // 2. 处理表单数据
    .then(() => {
      return {
        id: parameter.value.mail.id,
        title: parameter.value.mail.title,
        mailType: parameter.value.mail.mailType,
        sendingRange: parameter.value.mail.sendingRange,
        message: parameter.value.mail.message,
        orgId: parameter.value.mail.sendingRange === 1 ? parameter.value.mail.orgId : undefined,
        roleIds: parameter.value.mail.sendingRange === 2 ? parameter.value.mail.roleIds : undefined,
        userIds: parameter.value.mail.sendingRange === 3 ? parameter.value.mail.userIds : undefined
      };
    })
    // 3. 提交表单
    .then(formData => {
      return parameter.value.submitApi!(formData);
    })
    // 4. 提交结果处理
    .then(({ data }) => {
      if (data) {
        ElMessage.success({ message: `${parameter.value.title}成功！` });
        parameter.value.getTableList!();
        dialogVisible.value = false;
      } else {
        ElMessage.error({ message: `${parameter.value.title}失败！` });
      }
    })
    // 5. 异常处理
    .catch((error: Error) => {
      if (error.message) ElMessage.error({ message: `${parameter.value.title}异常：${error.message}` });
      else ElMessage.error({ message: "请检查表单数据是否填写完整！" });
    });
};

// 暴露给父组件的属性和方法
defineExpose({
  acceptParams
});
</script>
